package yesjava.news.web;

import yesjava.news.entity.User;
import yesjava.news.service.UserService;
import yesjava.news.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 没有导入Servlet api
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        User user = userService.login(new User(name, password))  ;
        boolean success = (user!=null);
        if(success){
            request.getSession().setAttribute("currentUserId",user.getId());
            request.getSession().setAttribute("currentUserName",user.getName());
        }
        String msg = "";
        String path = null;
        if(success){
            //获取登录前的路径
            String lastURI = (String) request.getSession().getAttribute("lastURI");
            path= (lastURI!=null?lastURI:"/WEB-INF/page/main.jsp");
            if(lastURI!=null){//  清空登录前的路径
                request.getSession().setAttribute("lastURI",null);
                response.sendRedirect(request.getContextPath()+path);
                return;
            }

        }else{
            msg = "用户名或密码错误";
            request.setAttribute("msg",msg);
            path= "/WEB-INF/page/login.jsp";
        }
        request.getRequestDispatcher(path).forward(request,response);

    }
}
